// 这是一个简单的echo_udp
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
// ./udp_client ip port
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "正确用法:" << "./udp_client server_ip server_port" << endl;
    }
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cerr << "套接字创建失败" << endl;
    }
    cout << "套接字创建成功" << endl;

    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(argv[1]);
    server.sin_port = htons(stoi(argv[2]));

    while (true)
    {
        string inbuffer;
        cout << "请输入你要发送的信息:";
        getline(cin, inbuffer);
        int n = sendto(sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr *)&server, sizeof(server));

        char read_str[1024];
        struct sockaddr_in peer;
        socklen_t len = sizeof(peer);
        int m = recvfrom(sockfd, read_str, sizeof(read_str), 0, (struct sockaddr *)&peer, &len);
        if (m > 0)
        {
            read_str[m] = '\0';
            cout << "from server # " << read_str << endl;
        }
    }

    return 0;
}